package org.acghub.mtdb.xmlgen.maker.bean;

import org.acghub.mtdb.common.Bean;
import org.acghub.mtdb.common.Config;
import org.acghub.mtdb.common.ObjectUtil;
import org.acghub.mtdb.common.Var;
import org.acghub.mtdb.util.StringUtil;
import org.acghub.mtdb.xmlgen.Maker;

import java.io.PrintStream;

/**
 * @author zhouhe
 */
public class BeanHashCodeMaker extends Maker<Bean> {
    private final PrintStream ps;
    private final String prefix;

    public BeanHashCodeMaker(Bean inner, Config config, PrintStream ps, String prefix) {
        super(inner, config);
        this.ps = ps;
        this.prefix = prefix;
    }

    @Override
    public void make() throws Exception {
        ps.println(prefix + "@Override");
        ps.println(prefix + "public int hashCode() {");
        ps.println(StringUtil.concat(prefix, StringUtil.TAB) + "int hash = this.getObjId().intValue();");
        for (Var var : inner().getVars()) {
            ps.printf(StringUtil.concat(prefix, StringUtil.TAB) + "if (%s(this.%s)){\n", ObjectUtil.NON_NULL, var.getName());
            ps.printf(StringUtil.concat(prefix, StringUtil.TAB, StringUtil.TAB) + "hash ^= %s(this.%s);\n", ObjectUtil.HASHCODE, var.getName());
            ps.println(StringUtil.concat(prefix, StringUtil.TAB) + "}");
        }
        ps.println(StringUtil.concat(prefix, StringUtil.TAB) + "return hash;");
        ps.println(prefix + "}");
        ps.println();
    }
}
